import { Component, OnInit, OnDestroy, Input, Output, EventEmitter } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { Subject } from "rxjs/Subject";
import { Subscription } from "rxjs/Subscription";
import { CmHttp } from "CmHttp";
import { SheetDataType, EntrustPostType, ShowDataType, StrategyRequestType } from "./vtradeterminal.model";
import { VtradeTerminalService } from "./vtradeterminal.service";
import { HsClientService } from "./../hs-client.service";
import { UserService, User } from "user";

export class BidAskValue {
  amount: string;
  price: string;
  bidOrAsk: boolean;  // 0: ask 卖, 1: bid 买
}

export const BUYIN = 'buyin';
export const SALEOUT = 'saleout';

@Component({
  selector: 'vtrade-terminal',
  templateUrl: 'vtradeterminal.component.html',
  styleUrls: ['vtradeterminal.component.less']
})
export class VtradeTerminalComponent implements OnInit, OnDestroy {
  @Input() stockSource;
  @Input() focusSource;
  @Input() summarySource;
  @Output() onModal = new EventEmitter();
  @Output() updateChart = new EventEmitter();
  // 可以有效交易的股票数据源
  validTradeSource = new Subject();
  bidAskValueSource = new Subject();
  emptySource = new Subject();
  buyinTypeSource = Observable.of('buyin');
  saleoutTypeSource = Observable.of('saleout');
  bottomPrice: number;
  topPrice: number;
  currentUser: User;
  // 策略消息推送sub
  strategySenderSub = new Subject();
  constructor(private http: CmHttp
    , private vts: VtradeTerminalService
    , private hsClient: HsClientService
    , private userService: UserService) { }
  stockSubscription: Subscription;
  focusSubscription: Subscription;
  userSubscription: Subscription;
  strategySubscription: Subscription;

  ngOnInit() {
    // 设定涨停价/跌停价
    this.stockSubscription = this.stockSource.subscribe(stock => {
      this.topPrice = stock['up_price'];
      this.bottomPrice = stock['down_price'];
      // 过滤不可以交易的指数和板块数据
      if (stock.market.indexOf('MRI') === -1 && stock.market.indexOf('XBHS') === -1) {
        this.emptySource.next(false);
        this.validTradeSource.next(stock);
      } else {
        this.emptySource.next(true);
        console.debug(`%c 不能交易的股票: ${stock.symbol}, ${stock.name}, ${stock.market}`, 'color: #F09');
      }
    });

    // 高亮哪一个交易终端
    this.focusSubscription = this.focusSource.subscribe(isSell => {
      isSell ? this.focusVtrade('saleout') : this.focusVtrade('buyin');
    });

    // 订阅当前用户的信息
    this.userSubscription = this.userService.userSub.subscribe(u => {
      this.currentUser = u;
    });

    // 向后端发送策略推送
    this.strategySubscription = this.strategySenderSub.subscribe((res: any) => {
      // 老师向后台发送策略
      if (this.currentUser && this.currentUser.role === 'teacher') {
        let data: StrategyRequestType = {
          tradeId: res.tradeId,
          type: res.type,
          price: res.tradeObj.price,
          amount: res.tradeObj.amount,
          symbol: res.tradeObj.symbol,
          symbolName: res.tradeObj.name
        };
        this.vts.postStrategyMsg(data).subscribe(res => {
          console.debug('策略消息推送成功');
        }, err => {
          console.warn('策略消息推送失败: ', err);
        });
      }
    });
  }

  ngOnDestroy() {
    this.stockSubscription ? this.stockSubscription.unsubscribe() : null;
    this.focusSubscription ? this.focusSubscription.unsubscribe() : null;
    this.userSubscription ? this.userSubscription.unsubscribe() : null;
    this.strategySubscription ? this.strategySubscription.unsubscribe() : null;
  }


  // 点击涨停价跌停价更新到交易终端的价格位置
  updatePrice(val: string) {
    if (!this.isBuyinFocus && !this.isSaleoutFocus) return;
    let priceObj = Object.assign({}, { price: val }, { type: this.isBuyinFocus ? 'buyin' : 'saleout' });
    this.bidAskValueSource.next(priceObj);
  }
  // 点击买卖五档更新价格到交易终端的价格位置
  updateBidAskPrice(val: BidAskValue) {
    if (!this.isBuyinFocus && !this.isSaleoutFocus) return;
    let priceObj = Object.assign({}, val, { type: this.isBuyinFocus ? 'buyin' : 'saleout' });
    this.bidAskValueSource.next(priceObj);
  }

  // 通知modal显示委托单信息
  isShowVtradeModal = false;
  showModal(data: SheetDataType) {
    // console.debug('showmodal data:', data);
    this.vts.setSheetData(data);
    this.isShowVtradeModal = true;
  }

  // 聚焦买入或者卖出
  isBuyinFocus = false;
  isSaleoutFocus = false;
  focusVtrade(type: string) {
    // console.debug('focus vtrade:', type);
    switch (type) {
      case 'buyin':
        this.isBuyinFocus = true;
        this.isSaleoutFocus = false;
        break;
      case 'saleout':
        this.isBuyinFocus = false;
        this.isSaleoutFocus = true;
        break;
    }
  }

  // 确认交易
  onConfirm(data: Object) {
    // type: type,
    // buyin: this.buyinObj,
    // saleout: this.saleoutObj
    //  ShowDataType {
    //   symbol: string;
    //   name: string;
    //   price: string;
    //   amount: number;
    //   account: string;
    // }
    console.debug('trade data: ', data);
    // 关闭委托单详情
    this.isShowVtradeModal = false;

    switch (data['type']) {
      case BUYIN:
        this.buyinAction(data['buyin']);
        break;
      case SALEOUT:
        this.saleoutAction(data['saleout']);
        break;
    }
  }

  // 买入交易委托
  private buyinAction(buyinObj: ShowDataType) {
    let data: EntrustPostType = {
      exchange_type: buyinObj['market'].indexOf('XSHG') > -1 ? "1" : "2",  // 1 for 上证, 2 for 深证
      stock_account: buyinObj.account,
      stock_code: buyinObj.symbol.replace(/(\.[a-zA-Z]*)/g, ""),
      entrust_amount: buyinObj.amount,
      entrust_price: buyinObj.price,
      entrust_bs: "1",  // 1 for buyin, 2 for saleout
      entrust_prop: "0",  // 0 for 买卖
    };
    console.log('confirm buyin:', buyinObj, data);
    this.hsClient.postEntrust(data).subscribe(res => {
      console.log('买入委托交易数据:', res);
      // 交易错误
      if (res.isError) {
        let msg = res.message;
        this.onModal.next(msg);
        return;
      } else {
        let tradeId = res['data'][0]['entrust_no'];
        let msg = `委托成功，委托单号为${tradeId}`;
        this.onModal.next(msg);
        this.updateEntrustSheetAndSummary(res);
        // 推送策略
        this.strategySenderSub.next({
          tradeId: tradeId, type: "buy", tradeObj: buyinObj
        });
      }
    }, err => {
      console.warn("买入委托交易异常:", err);
      this.isShowVtradeModal = false;
      let msg = err.message;
      this.onModal.next(msg);
    });
  }

  // 卖出交易委托
  private saleoutAction(saleoutObj: ShowDataType) {
    let data: EntrustPostType = {
      exchange_type: saleoutObj['market'].indexOf('XSHG') > -1 ? "1" : "2",  // 1 for 上证, 2 for 深证
      stock_account: saleoutObj.account,
      stock_code: saleoutObj.symbol.replace(/(\.[a-zA-Z]*)/g, ""),
      entrust_amount: saleoutObj.amount,
      entrust_price: saleoutObj.price,
      entrust_bs: "2",  // 1 for buyin, 2 for saleout
      entrust_prop: "0",  // 0 for 买卖
    };
    console.log('confirm saleout:', saleoutObj, data);
    this.hsClient.postEntrust(data).subscribe(res => {
      console.log('卖出委托交易数据:', res);
      // 交易错误
      if (res.isError) {
        let msg = res.message;
        this.onModal.next(msg);
        return;
      } else {
        let tradeId = res['data'][0]['entrust_no'];
        let msg = `委托成功，委托单号为${tradeId}`;
        this.onModal.next(msg);
        this.updateEntrustSheetAndSummary(res);

        // 推送策略
        this.strategySenderSub.next({
          tradeId: tradeId, type: "sell", tradeObj: saleoutObj
        });
      }
    }, err => {
      console.warn("卖出委托交易异常:", err);
      this.isShowVtradeModal = false;
      let msg = err.message;
      this.onModal.next(msg);
    });
  }

  // 点击买入、卖出后提示的错误信息
  onError(error_info: string) {
    this.onModal.next(error_info);
  }

  // 成功委托之后更新委托单数据和账户数据
  private updateEntrustSheetAndSummary(res) {
    if (!!res['data']) {
      this.hsClient.broadcast.next();
    }
  }
}